package com.masterclient.app.businessmodule.minemodule.index;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.application.BaseApplication;
import com.eoner.baselib.fragment.FCBaseFragment;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.eoner.baselib.utils.status.StatusBarUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.bean.firstpager.SignBean;
import com.eoner.baselibrary.bean.personal.CustomerOrderInfo;
import com.eoner.baselibrary.bean.personal.MedalDetailBean;
import com.eoner.baselibrary.bean.personal.MedalItemBean;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.managerlibrary.user.callback.UserDataCallBack;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.router.intercept.FCBaseIntercept;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.businessmodule.minemodule.contract.PersonalContract;
import com.masterclient.app.businessmodule.minemodule.contract.PersonalPresenter;
import com.masterclient.app.businessmodule.minemodule.index.animation.PersonAnimation;
import com.masterclient.app.businessmodule.minemodule.index.medal.PersonMedalDialog;
import com.masterclient.app.businessmodule.minemodule.index.tutor.InviteInfoBean;
import com.masterclient.app.businessmodule.minemodule.index.view.PersonFunctionView;
import com.masterclient.app.businessmodule.minemodule.index.view.PersonHeaderView;
import com.masterclient.app.businessmodule.minemodule.index.view.PersonOrderListView;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.utils.CommonUtil;
import com.eoner.uikit.header.MyRefreshHead;
import com.masterclient.app.widget.MaterialBadgeTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;

/**
 * 作者：sean
 * 创建时间：2017/6/7 18:05
 * 功能说明：
 */

public class PersonalFragment extends FCBaseFragment<PersonalPresenter> implements PersonalContract.View,
        PersonFunctionView.PersonFunctionViewItemClickListener, PersonHeaderView.PersonHeadViewListener {

    public static String TAG = "PersonalFragment";

    //标题栏
    @BindView(R.id.view_title)
    View viewTitle;
    //下拉刷新
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.roundImage)
    ImageView roundImage;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.iv_level_bg)
    ImageView ivLevelBg;
    @BindView(R.id.view_code)
    LinearLayout llCode;
    @BindView(R.id.tv_authentication_name)
    TextView tvAuthenticationName;
    @BindView(R.id.iv_unread)
    MaterialBadgeTextView iv_unread;
    //top
//    @BindView(R.id.person_sign_in)
//    PersonTopItemView personSignIn;

//    @BindView(R.id.person_walf_in)
//    PersonTopItemView personWalf;

    //header
//    @BindView(R.id.person_header_view)
//    PersonHeaderView mPersonHeaderView;
    //数据view
//    @BindView(R.id.ll_person_data)
//    PersonDataView mPersonDataView;
    //订单分类列表
    @BindView(R.id.ll_person_order)
    PersonOrderListView mOrderListView;
    //banner
//    @BindView(R.id.ll_banner)
//    LinearLayout llBanner;
//    @BindView(R.id.banner)
//    Banner banner;
    //工具服务
    @BindView(R.id.person_func_view)
    PersonFunctionView mPersonFunctionView;
    //动画
    private PersonAnimation mPersonAnimation;
    //勋章弹窗
    private WeakReference<PersonMedalDialog>mPersonMedalDialog;

    private String signUrl;
    private String welfareUrl;
    private boolean isSign = false;
    private CustomerOrderInfo.DataBean dataBean;

    public static PersonalFragment newInstance() {
        return new PersonalFragment();
    }

    @Override
    protected int requireGetLayoutId() {
        return R.layout.fragment_personal;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setVisibility(View.GONE);
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        //2.设置状态栏
        StatusBarUtils.immersive(getActivity());
        StatusBarUtils.setPaddingSmart(getActivity(), viewTitle);

        //创建动画
        mPersonAnimation = new PersonAnimation();
        //初始化订单分类列表
        mOrderListView.initView();
        //设置工具服务列表点击监听
        mPersonFunctionView.setPersonFunctionViewItemClickListener(this);
        //初始化数据view
//        mPersonDataView.initView();
        //设置头部点击监听
//        mPersonHeaderView.setPersonHeadViewListener(this);

        refreshLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
//        personSignIn.setVisibility(View.GONE);
//        personSignIn.showData("签到","data_sign.json",-1);

//        if (UserDataManager.getInstance().isSystemLogin()) { //曾经登录过没有退出
//            //TODO:fix
            refreshHeaderImage(UserDataManager.getInstance().getHeadImgUrl());
            refreshNickName(UserDataManager.getInstance().getNickName());
            ViewTransformUtil.glideImageView(getContext(), UserDataManager.getInstance().getLevel_bg(), ivLevelBg, R.mipmap.defaults_1);
            tvCode.setText("邀请码："+UserDataManager.getInstance().getInviteCode());
//            mPersonHeaderView.setViewState(PersonHeaderView.PersonHeaderViewState.PERSON_HEAD_LOGIN_NO_DATA,"",dataBean!=null?dataBean.getMedal_list():null);
//        } else {
//            mPersonHeaderView.setViewState(PersonHeaderView.PersonHeaderViewState.PERSON_HEAD_NO_LOGIN,"",dataBean!=null?dataBean.getMedal_list():null);
//        }

        if (!UserDataManager.getInstance().getCheckIdCardStatus().equals("1")){
            tvAuthenticationName.setText("实名认证");
        }else {
            tvAuthenticationName.setText("已实名认证");
        }


        refreshLayout.setOnRefreshListener(refreshLayout -> {
            requestCustomerOrderIndex();
        });
        mPresenter.mRxManager.mRxBus.OnEvent(mPresenter.mRxManager.mRxBus.register(Config.SUBMIT_ORDER), new Consumer<Object>() {
            @Override
            public void accept(Object o) {
                requestCustomerOrderIndex();
            }
        });

        mPresenter.mRxManager.mRxBus.OnEvent(mPresenter.mRxManager.mRxBus.register(Config.LOGOUT_SUCCESS), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                ViewTransformUtil.glideImageView(getContext(), "", ivLevelBg, R.mipmap.defaults_1);
                refreshHeaderImage(R.mipmap.user_head_default_icon);
                refreshNickName("注册/登录");
                llCode.setVisibility(View.INVISIBLE);
//                mPersonHeaderView.setViewState(PersonHeaderView.PersonHeaderViewState.PERSON_HEAD_NO_LOGIN,"",dataBean!=null?dataBean.getMedal_list():null);
                mOrderListView.initBadges();
//                mPersonDataView.initData();

//                if (dataBean.getSign() != null && dataBean.getSign().isIs_show()) {
//                    personSignIn.setVisibility(View.VISIBLE);
//                    personSignIn.showData("签到","data_sign.json",-1);
//                } else {
//                    personSignIn.setVisibility(View.GONE);
//                }
//                personWalf.setVisibility(View.GONE);
                mPersonFunctionView.getIvUnread().setVisibility(View.INVISIBLE);
                //TODO:通知首页刷新
                EventBusManager.post(EventBusManager.createHomeRefreshEvent());
            }
        });
        llCode.setVisibility(View.INVISIBLE);
        //首次加载
        requestCustomerOrderIndex();
    }

    public void setStatusBar(Activity activity) {
        StatusBarUtil.transparencyBar(activity);
    }

    @Override
    public void onResume() {
        MobclickAgent.onEvent(getContext(), "page_customer_index");
        if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN))) {
            mPersonFunctionView.getLottieTask().setVisibility(View.GONE);
        }
        MainActivity mainActivity = (MainActivity)getActivity();
        //TODO:只有在我的显示的时候再执行
        if (mainActivity != null && mainActivity.curPosition == 3) {
            requestCustomerOrderIndex();
        }
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            StatusBarUtil.transparencyBar(getActivity());

            if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN))) {
            } else {
                mPersonFunctionView.getLottieTask().setVisibility(View.GONE);
            }
            requestCustomerOrderIndex();
        }
    }

    private void requestCustomerOrderIndex() {

        UserDataManager.getInstance().requestCustomerOrderIndex(new UserDataCallBack() {
            @Override
            public void onSuccess(CustomerOrderInfo orderInfo) {
                CustomerOrderInfo.DataBean dataBean = orderInfo.getData();
                if (dataBean != null) {
                    showCustomerOrderInfo(dataBean);
                } else {
                    if (refreshLayout != null) {
                        refreshLayout.finishRefresh(false);
                    }
                }
            }

            @Override
            public void onFailed(String errMsg) {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh(false);
                }
            }
        });
    }

    @OnClick({R.id.view_head,R.id.rl_msg,R.id.view_code,R.id.view_authentication,R.id.view_invitation})
    void onClick(View view) {
        switch (view.getId()) {
//            case R.id.person_walf_in:
//                if (UserDataManager.getInstance().isSystemLogin()) {
//                    if (TextUtils.isEmpty(welfareUrl)) return;
//                    startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", welfareUrl}});
//                } else {
//                    startActivity(new Intent(getContext(), QuickLoginActivity.class));
//                }
//                break;
//            case R.id.person_sign_in:
//                if (UserDataManager.getInstance().isSystemLogin()) {
//                    if (TextUtils.isEmpty(signUrl)) return;
//                    if (isSign) {
//                        startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", signUrl}});
//                    } else {
//                        mPresenter.getSign();
//                    }
//                } else {
//                    startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "我的"}});
//                }
//                break;
            case R.id.view_head: {
                if (!UserDataManager.getInstance().isSystemLogin()) {
                    startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "我的"}});
                } else {
                    ARouter.getInstance().build(FCRouterPath.USER_PERSONAL_PATH).navigation(getContext(),new FCBaseIntercept());
                }
            }
            break;
            case R.id.rl_msg: {
                if (!UserDataManager.getInstance().isSystemLogin()) {
                    startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "我的"}});
                } else {
                    iv_unread.setVisibility(View.GONE);
                    CommonUtil.goAnyWhere(getActivity(), SystemConfigStorage.getInstance().getMessageCenterUrl(), "", "", "", "");
                }
            }
            break;
            case R.id.view_code: {
                if (!TextUtils.isEmpty(UserDataManager.getInstance().getInviteCode())){
                    ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setPrimaryClip(ClipData.newPlainText(null, UserDataManager.getInstance().getInviteCode()));
                    showToast("已复制到粘贴板");
                }
            }
            break;
            case R.id.view_authentication: {
                if (UserDataManager.getInstance().isSystemLogin()) {
                    if (!UserDataManager.getInstance().getCheckIdCardStatus().equals("1")){
                        tvAuthenticationName.setText("实名认证");
                        ARouter.getInstance().build(FCRouterPath.SETTING_AUTH_PATH)
                                .navigation(getActivity(),new FCBaseIntercept());
                    }else {
                        tvAuthenticationName.setText("已实名认证");
                        ToastUtil.showToast("您已通过实名认证");
                    }
                } else {
                    startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "我的"}});
                }
            }
            break;
            case R.id.view_invitation: {
                if (UserDataManager.getInstance().isSystemLogin()) {
                    if (dataBean.getStatus().equals("1")){
                        mPresenter.getShareInfo();
                    }else {
                        ConfirmDialog dialog = new ConfirmDialog(getActivity(), "", "该账户已冻结，无法邀请好友，如有疑问，请咨询客服", null, "取消"
                                ,"确定", 1, "#333333");
                        dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                            @Override
                            public void cancel() {
                                dialog.dismiss();
                            }

                            @Override
                            public void confirm() {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    }
                } else {
                    startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "我的"}});
                }
            }
            break;
            default:
        }
    }

    @Override
    public void onClickLiveItem() {
//        if (UserDataManager.getInstance().isSystemLogin()) {
//            if (dataBean != null && dataBean.isIs_anchor()) {
//                Fragment fragment1 = (Fragment) ARouter.getInstance().build(AroutePath.MY_LIVE_LIST_FRAGMENT)
//                        .navigation();
//                FragmentHostActivity.openFragment(getActivity(), fragment1);
//            } else {
//                mPresenter.getApplyStatus();
//            }
//        } else {
//            startActivity(new Intent(getContext(), QuickLoginActivity.class));
//        }
    }


    public void showCustomerOrderInfo(CustomerOrderInfo.DataBean dataBean) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
        this.dataBean = dataBean;
        if (dataBean.getWelfare() != null) {
            welfareUrl = dataBean.getWelfare().getWelfare_url();
        }

        signUrl = TextUtils.isEmpty(dataBean.getSign().getSign_url()) ? "" : dataBean.getSign().getSign_url();
        progressCustomerOrderData();
    }

    private void progressCustomerOrderData() {
        //TODO:刷新顶部
//        if (dataBean.getSign() != null && dataBean.getSign().isIs_show()) {
//            isSign = dataBean.getSign().isIs_signed();
//            personSignIn.setVisibility(View.VISIBLE);
//            if (isSign){
//                personSignIn.showData("已签到","data_sign.json",-1);
//            } else {
//                personSignIn.showData("签到","data_sign.json",-1);
//            }
//        } else {
//            personSignIn.setVisibility(View.GONE);
//        }
        //TODO:刷新数据模块
//        mPersonDataView.refreshData(dataBean);
        //TODO:刷新banner
        refreshBannerView();
        //TODO:刷新功能模块
        mPersonFunctionView.refreshData(dataBean,signUrl,mPersonAnimation);

        if (UserDataManager.getInstance().isSystemLogin()) {
            llCode.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(dataBean.getCustomer_id())  || dataBean.getCustomer_id().equals("0")) {
                //退出状态
                SPUtils.getInstance().remove(Config.TASK_TIME_SHARE_GOODS);
                //TODO:清除用户信息
                UserDataManager.getInstance().clearLoginInfo();
                if (BaseApplication.getContext() != null){
                    //TODO:跳转主页
                    UtilActivity.finishStartNum(0,UtilActivity.getActivitySize());
                    //TODO:通过路由跳转
                    ARouter.getInstance().build(AroutePath.MAIN_ACTIVITY).withString("code", "1101").navigation();
                }
            } else {
//                personWalf.setVisibility(View.VISIBLE);
//                if (dataBean.getWelfare()!=null && Integer.parseInt(dataBean.getWelfare().getWelfare_num()) > 0) {
//                    personWalf.showData("福利","data_walf.json",Integer.parseInt(dataBean.getWelfare().getWelfare_num()));
//                } else {
//                    personWalf.showData("福利","data_walf.json",0);
//                }
                //TODO:刷新头部
//                mPersonHeaderView.setViewState(PersonHeaderView.PersonHeaderViewState.PERSON_HEAD_LOGIN_HAS_DATA,dataBean.getNo_medal_notice(),dataBean!=null?dataBean.getMedal_list():null);
//                mPersonHeaderView.refreshVipImage(dataBean);
//                //刷新头像
                refreshHeaderImage(dataBean.getHeadimgurl());
                refreshNickName(dataBean.getNick_name());
                ViewTransformUtil.glideImageView(getContext(), dataBean.getLevel_bg(), ivLevelBg, R.mipmap.defaults_1);
                tvCode.setText("邀请码："+dataBean.getInvite_code());

                if (!dataBean.getCheck_idcard_status().equals("1")){
                    tvAuthenticationName.setText("实名认证");
                }else {
                    tvAuthenticationName.setText("已实名认证");
                }
                if (Integer.parseInt(dataBean.getMessage_num()) >= 1) {
                    iv_unread.setBadgeCount(dataBean.getMessage_num());
                    iv_unread.setVisibility(View.VISIBLE);
                } else {
                    iv_unread.setVisibility(View.GONE);
                }
                //TODO:刷新数据模块
//                mPersonDataView.refreshData(dataBean);
                //TODO:刷新订单分类列表
                //待付款
                mOrderListView.updateDfkCount(dataBean.getPending_num());
                //待发货
                mOrderListView.updateDfhCount(dataBean.getNo_shipped_num());
                //待收货
                mOrderListView.updateDshCount(dataBean.getShipped_num());
                //待评价
                mOrderListView.updateDpjCount(dataBean.getNo_review_num());
                //售后
                mOrderListView.updateShouhouCount(dataBean.getRefund_num());
            }

        } else {
            refreshNoLoginState();
        }
    }

    private void refreshNoLoginState() {
//        personWalf.setVisibility(View.GONE);
        //TODO:刷新头部
        refreshHeaderImage(R.mipmap.user_head_default_icon);
        refreshNickName("注册/登录");
//        mPersonHeaderView.setViewState(PersonHeaderView.PersonHeaderViewState.PERSON_HEAD_NO_LOGIN,"",dataBean!=null?dataBean.getMedal_list():null);
        //TODO:刷新订单分类列表
        mOrderListView.initBadges();
        //TODO:刷新数据模块
//        mPersonDataView.initData();
    }

    private void refreshHeaderImage(String image){
        ViewTransformUtil.glideImageView(getContext(), image,roundImage,
                new CropCircleWithBorderTransformation(0,0x0A3D2529), R.mipmap.user_head_default_icon);
    }

    private void refreshHeaderImage(int image) {
        roundImage.setImageResource(image);
    }

    public void refreshNickName(String name) {
        if (name != null && name.length() > 0) {
            tvUserName.setText(name);
        } else {
            tvUserName.setText("");
        }
    }

    private void refreshBannerView() {
//        if (dataBean.getAd_list() != null && dataBean.getAd_list().size() > 0) {
//            llBanner.setVisibility(View.VISIBLE);
//            List<String> imgs = new ArrayList<String>();
//            List<BannerNewItemBean> featuresBeans = dataBean.getAd_list();
//            for (BannerNewItemBean featuresBean : featuresBeans) {
//                imgs.add(featuresBean.getImage());
//            }
//            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
//            banner.setImageLoader(new PersonBannerImageLoader(ScreenUtils.getScreenWidth(), ScreenUtils.dp2px(85), ScreenUtils.dp2px(14)));
//            banner.setImages(imgs);
//            banner.setBannerAnimation(Transformer.Default);
//            banner.isAutoPlay(true);
//            banner.setDelayTime(5000);
//            banner.setIndicatorGravity(BannerConfig.CENTER);
//            banner.start();
//            banner.setOnBannerListener(new OnBannerListener() {
//                @Override
//                public void OnBannerClick(int position) {
//                    MobclickAgent.onEvent(getContext(), "click_banner");
//                    BannerNewItemBean bannerBean = featuresBeans.get(position);
//                    CommonUtil.goNewAnyWhere(getContext(),bannerBean.getTarget_platform(),bannerBean.getTarget_message(),bannerBean.getTarget(), bannerBean.getTarget_id(), bannerBean.getImage(), bannerBean.getS_ad_name(), bannerBean.getS_ad_id());
//                }
//            });
//        } else {
//            llBanner.setVisibility(View.GONE);
//        }
    }

    @Override
    public void signData(SignBean bean) {
        if ("0".equals(bean.getSh_success())){
            startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", signUrl}});
            ToastUtil.showToast(bean.getSh_tips());
        }else {
            Intent intent = new Intent(getActivity(), BridgeActivity.class);
            intent.putExtra("url", signUrl);
            intent.putExtra("sign_day", bean.getSh_sign_day_num());
            intent.putExtra("sign_bupiao", bean.getSh_bupiao());
            intent.putExtra("sign_integral", bean.getSh_integral());
            intent.putExtra("sign_coupon", bean.getSh_coupon());
            intent.putParcelableArrayListExtra("sign_list", (ArrayList<? extends Parcelable>) bean.getSh_recommend_product());
            startActivity(intent);
        }
    }

    @Override
    public void getMedalDetail(MedalDetailBean detailBean) {
        if (mPersonMedalDialog !=null && mPersonMedalDialog.get() != null && mPersonMedalDialog.get().isShowing()) {
            return;
        }
        PersonMedalDialog dialog = new PersonMedalDialog.Builder(getContext())
                .setDetailBean(detailBean).create();
        dialog.show();
        mPersonMedalDialog = new WeakReference<PersonMedalDialog>(dialog);
    }

    /**
     * 弹出勋章
     * */
    @Override
    public void onClickMedal(MedalItemBean itemBean) {
        mPresenter.requestMedalDetail(itemBean.getMedal_id());
    }

    @Override
    public void getShareInfoSuccess(InviteInfoBean bean) {
        InviteFriendDialog inviteFriendDialog = new InviteFriendDialog(getActivity(),bean.share_url,bean.nick_name,
                bean.headimgurl,bean.invite_code);
        inviteFriendDialog.show();
    }

    @Override
    public void getShareInfoFail(String msg) {

    }

    @Override
    public void onDestroy() {
        if (mPresenter != null && mPresenter.mRxManager != null && mPresenter.mRxManager.mRxBus != null) {
            mPresenter.mRxManager.mRxBus.unregister(Config.SUBMIT_ORDER);
            mPresenter.mRxManager.mRxBus.unregister(Config.LOGOUT_SUCCESS);
        }
        super.onDestroy();
    }
}
